<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
          
          </el-breadcrumb>
        <el-card >
          
              <el-row :gutter="20"> 
                <el-col :span="7">  <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserlist">
             
                    <el-button slot="append" icon="el-icon-search" @click="getUserlist"></el-button>
                  </el-input></el-col>
                <el-col :span="4"><el-button type="primary" @click="addVisible=true">添加用户</el-button></el-col>
              </el-row>
              <el-table
              :data="userList"
              style="width: 100%" border stripe>
              <el-table-column
                 type="index" label="#">
              </el-table-column>
              <el-table-column
                prop="username"
                label="姓名"
                width="180">
              </el-table-column>
              <el-table-column
                prop="email"
                label="邮箱"
                width="180">
              </el-table-column>
              <el-table-column
                prop="mobile"
                label="电话">
              </el-table-column>
              <el-table-column
              prop="role_name"
              label="角色">
            </el-table-column>
            <el-table-column
        
            label="状态">
            <template slot-scope='scope'>
             
                <el-switch
  v-model="scope.row.mg_state" @change="userStateChange(scope.row)"
 >
</el-switch>
            </template>
          </el-table-column>

          <el-table-column
          
          label="操作">
          <template slot-scope='scope'>
            <el-button type="primary" icon="el-icon-edit" @click='handleEdite(scope.row.id)'></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false" >
                <el-button type="warning" icon="el-icon-setting" @click="setRole(scope.row)"></el-button>
              </el-tooltip>

<el-button type="danger" icon="el-icon-delete" @click='removeUser(scope.row.id)'></el-button>
 
        </template>
        </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page=" queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
          </el-card>
          <!-- 添加用户对话 -->
          <el-dialog
  title="提示"
  :visible.sync="addVisible"
  width="30%" @close="addClose"
   >
   <el-form :model="addForm" :rules="addFormRule" ref="addFormRef" label-width="70px"  >
    <el-form-item label="用户名" prop="username">
      <el-input v-model="addForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
        <el-input v-model="addForm.password"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="addForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="addForm.mobile"></el-input>
      </el-form-item>
    </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addVisible = false" >取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
</el-dialog>
<!-- 修改  -->
<el-dialog
title="修改用户"
:visible.sync="editeVisible"
width="30%" @close="editeClose"
 >
 <el-form :model="editeForm" :rules="editeFormRule" ref="editeFormRef" label-width="70px"  >
  <el-form-item label="用户名" prop="username" >
    <el-input v-model="editeForm.username" disabled></el-input>
  </el-form-item>
   
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="editeForm.email"></el-input>
    </el-form-item>
    <el-form-item label="手机" prop="mobile">
      <el-input v-model="editeForm.mobile"></el-input>
    </el-form-item>
  </el-form>
<span slot="footer" class="dialog-footer">
  <el-button @click="editeVisible = false" >取 消</el-button>
  <el-button type="primary" @click="editeUserinfo">确 定</el-button>
</span>
</el-dialog>
<!-- f分配角色对话框 -->
<el-dialog
  title="分配角色"
  :visible.sync="setRoleVisible"
  width="30%" @close="setRoleClosed"
  >
  <p>当前用户：{{userInfo.username}}</p>
  <p>当前角色：{{userInfo.role_name}}</p>
  <p>分配新角色：
    <el-select v-model="selectedRole" placeholder="请选择">
        <el-option
          v-for="item in roleList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id">
        </el-option>
      </el-select>
  </p>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRole">确 定</el-button>
  </span>
</el-dialog>
    </div>
</template>
<script>
    export default {
data() {
    var checkEmail = (rule, value, callback) => {
       const regEail=/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
       if(regEail.test(value)){
           return callback()
       }
       callback(new Error('请输入合法邮箱'))
    }
    var checkMobile = (rule, value, callback) => {
        const regMoble= /^1[3456789]\d{9}$/
       if(regMoble.test(value)){
           return callback()
       }
       callback(new Error('请输入合法手机号'))
    }
    return {
         
        queryInfo:{
            query:'',
            pagenum:1,
            pagesize:2
        },
        userList:[],
        total:0,
        addVisible:false,
        addForm:{
            username:'',
            password:'',
            email:'',
            mobile:''
        },
        addFormRule:{
            username:[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
            ],
            password:[
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
            ],
            email:[
            { required: true, message: '请输入密码', trigger: 'blur' },
            {  validator:checkEmail, trigger: 'blur' }
            ],
            mobile:[
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator:checkMobile , trigger: 'blur' }
            ]
        },
        editeVisible:false,
        editeForm:{},
        editeFormRule:{
            
            email:[
            { required: true, message: '请输入密码', trigger: 'blur' },
            {  validator:checkEmail, trigger: 'blur' }
            ],
            mobile:[
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator:checkMobile , trigger: 'blur' }
            ]
        },
        setRoleVisible:false,
        userInfo:{},
        roleList:[],
        selectedRole:''



    }
},
created() {
    this.getUserlist()
},
methods: {
   async getUserlist(){
       const {data:res}=await this.$http.get('users',{params:this.queryInfo})
       console.log(res)
       if(res.meta.status!==200) return this.$message.error('获取用户列表失败')
       this.userList=res.data.users
       this.total=res.data.total
    },
    handleSizeChange(newSize){
      console.log(newSize)
      this.queryInfo.pagesize=newSize
      this.getUserlist()
    },
    handleCurrentChange(newPage){
console.log(newPage)
this.queryInfo.pagenum=newPage
      this.getUserlist()
    },
    // 监听switch状态的改变
    async userStateChange(userInfo){
       console.log(userInfo)
      const{data:res}=await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      console.log(res)
      if(res.meta.status!==200){
          userInfo.mg_state=!userInfo.mg_state
        return this.$message.error('更新用户状态失败')

      } 
        this.$message.success('更新用户状态成功')

    },
    addClose(){
        this.$refs.addFormRef.resetFields()
    },
   addUser(){
        this.$refs.addFormRef.validate( async valid=>{
            console.log(valid)
            if(!valid) return
          const{data:res} =await this.$http.post('users',this.addForm)
          if(res.meta.status!==201){
          userInfo.mg_state=!userInfo.mg_state
        return this.$message.error('添加用户状态失败')
        
      } 
      this.$message.success('添加用户状态成功')
      this.addVisible=false
      this.getUserlist()
        })
    },
    // 修改
  async handleEdite(id){
      console.log(id)
     
        const{data:res} =await this.$http.get(`users/${id}`)
        console.log(res)
          if(res.meta.status!==200){
        
        return this.$message.error('查询用户信息失败')
        
      } 
      this.editeForm=res.data
    this.editeVisible=true

    },
    editeClose(){
        this.$refs.editeFormRef.resetFields()
    },
    // 预判断
    editeUserinfo(){
        this.$refs.editeFormRef.validate(async valid=>{
            if(!valid) return
          const{data:res} =await this.$http.put('users/'+this.editeForm.id,{email:this.editeForm.email,mobile:this.editeForm.mobile})
          if(res.meta.status!==200){
            
        return this.$message.error('修改用户状态失败')
        
      } 
      this.editeVisible=false
      this.getUserlist()
      this.$message.success('修改用户状态成功')
      
     
        })
    },
    async removeUser(id) {
        console.log(id)
       
        
      const confirmResult = await this.$confirm('此操作将永久删除该文用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch((err) => {
           return err
        })
        console.log(confirmResult)
        // 如果没有catch抛出取消返回的错误信息浏览器会报错，必须有catch抛出错误
        // 确认：confirm
        // 取消:cancel
        if(confirmResult!=='confirm'){
 return this.$message.info('已经取消删除')
        }
        const{data:res} =await this.$http.delete(`users/${id}`)
        if(res.meta.status!==200){
            
            return this.$message.error('删除用户失败')
            
          } 
          this.$message.success('删除用户成功')
          this.getUserlist()
      },
     async setRole(userInfo){
         console.log(11)
         this.userInfo=userInfo
        const{data:res} = await this.$http.get('roles')
        if(res.meta.status !==200){
            return this.$message.error('获取角色失败')
        }
        this.roleList=res.data
          this.setRoleVisible=true
      },
    //   点击分配角色
     async saveRole(){
           if(!this.selectedRole){
               return this.$message.error('请选择分配用户角色')
           }
           console.log(this.userInfo.id)
           console.log(this.selectedRole)

            const{data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectedRole})
            if(res.meta.status!==200){
                
            return this.$message.error('更新失败')
            
          } 
          this.$message.success('更新成功')
        
          this.getUserlist()
          this.setRoleVisible=false
        },
        setRoleClosed(){
            this.selectedRole='',
            this.userInfo=[]
        }

    }
}
   
</script>
<style lang="less" scoped> 

</style>